package latin.service.impl;


import com.google.common.collect.Lists;
import latin.common.ServiceResponse;
import latin.dao.JavaMapper;
import latin.pojo.Java;
import latin.service.IJavaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

@Service("iJavaService")
public class JavaServiceImpl implements IJavaService {

    @Autowired
    private JavaMapper javaMapper;

    //查询java题库中的所有的id
    public List<Long> getAllId() {
        List<Long> longList = Lists.newArrayList();
        longList = javaMapper.getAllId();
        return longList;
    }

    //查询指定id的java的对象
    public ServiceResponse<Java> selectById(Long id) {
        Java java = javaMapper.selectByPrimaryKey(id);
        return ServiceResponse.createBySuccess(java);
    }

    //获取10道题

    public ServiceResponse<List<Java>> getJava() {
        //获取题库所有id
        List<Long> longList = Lists.newArrayList();
        longList = this.getAllId();
        List<Java> javaList = Lists.newArrayList();
        //题库没有题
        if (longList == null) {
            return ServiceResponse.createBySuccess("题库还没有题", null);
        } else {

            Random random = new Random();
            int l = random.nextInt(longList.size());

            javaList.add(javaMapper.selectByPrimaryKey(longList.get(l)));
            return ServiceResponse.createBySuccess(javaList);
        }


       /* //题库有题，但小于10；
        List<Java> javaList = Lists.newArrayList();
        if(longList.size() <= 10){
            for(long i : longList){
                javaList.add(javaMapper.selectByPrimaryKey(i));
            }
            return ServiceResponse.createBySuccess(javaList);
        }
        //题库有题，大于10；
        List<Long> list = Lists.newArrayList();
        if(longList.size() > 10){
            Random random =new Random();
            while (list.size() <= 10) {
                Long l =(long) random.nextInt(longList.size());
                if(!list.contains(l)){
                    list.add(l);
                    javaList.add(javaMapper.selectByPrimaryKey(l));
                }
                *//*continue;*//*
            }
            return ServiceResponse.createBySuccess(javaList);

        }*/

    }

    //添加java面试题；
    public ServiceResponse addJava(Java java) {
        int i = javaMapper.selectJava(java.getQuestion());
        if (i != 0) {
            return ServiceResponse.createByErrorMessage("此题已经存在");
        }
        int j = javaMapper.insert(java);
        if (j != 0) {
            return ServiceResponse.createBySuccessMessage("添加成功");
        } else {
            return ServiceResponse.createByErrorMessage("添加失败");
        }
    }


}


